<?php

namespace App\Http\Controllers\WeChat;

use App\Http\Controllers\Controller;
use App\Models\WeChat;
use App\Models\WeChatMaterial;
use Houdunren\WeChat\Material;
use Illuminate\Http\Request;

class MaterialController extends Controller
{

    public function index(Request $request)
    {
        //request->query()，获取url查询的值，
        $type = $request->query('type', 'image');
        $materials = WeChatMaterial::site()->module()->paginate(12);
        return view('wechat.material.index', compact('materials', 'type'));
    }


    public function create(Request $request)
    {

        $type = $request->query('type');
        if (!$type) {
            abort('403', '缺少type变量');
        }
        return view('wechat.material.create', compact('type'));
    }


    public function store(Request $request, WeChatMaterial $Material, Material $materialPackage)
    {
        $type = $request->query('type', 'image');
        //此处没有通过微信和服务器接口，所以，需要获取wechat的信息，appID,
        $materialPackage->init(WeChat::find($request->wechat_id));

        $info = $materialPackage->add('image', $request->input('content.picurl'));

        $Material->site_id = site()['id'];
        $Material->module_id = module()['id'];
        $Material->wechat_id = $request->wechat_id;
        $Material->type = $type;
        $Material->info = $info;
        $Material->content = $request->content;
        $Material->save();

        return response()->json(['route' => route('wechat.material.index'), 'message' => '图片素材上传成功']);

    }


    public function show(WeChatMaterial $material)
    {
        return $material;
    }


    public function edit(WeChatMaterial $material)
    {
        $type = request()->query('type', 'image');
        return view('wechat.material.edit', compact('material', 'type'));
    }


    public function update(Request $request, WeChatMaterial $Material, Material $materialPackage)
    {
        $type = $request->query('type', 'image');

        $materialPackage->init(WeChat::find($weChatMaterial['wechat_id']));
        $materialPackage->add($type, $request->input('content.picurl'));
        $materialPackage->delete($weChatMaterial['info']['media_id']);
        $material->wechat_id = $weChatMaterial['wechat_id'];
        $material->content = $request->content;
        $material->info = $info;
        $material->save();
        return response()->json(['route' => route('wechat.material.index'), 'message' => '素材修改成功']);
    }


    public function destroy(WeChatMaterial $material, Material $materialPackage)
    {
        //需要先删除微信服务器上的永久素材
        $materialPackage->init(WeChat::find($material['wechat_id']));

        $materialPackage->delete($material['info']['media_id']);
        $material->delete();

        return response()->json(['message' => '素材删除成功']);

    }
}
